package cn.iocoder.yudao.module.ai.service.operationendcompany;

import cn.iocoder.yudao.framework.exception.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.ai.controller.admin.operationendcompany.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.operationendcompany.OperationEndCompanyDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ai.dal.mysql.operationendcompany.OperationEndCompanyMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.ai.enums.ErrorCodeConstants.*;

/**
 * 运营中心-公司管理（煤矿管理） Service 实现类
 *
 * @author 侯俊青
 */
@Service
@Validated
public class OperationEndCompanyServiceImpl implements OperationEndCompanyService {

    @Resource
    private OperationEndCompanyMapper operationEndCompanyMapper;

    @Override
    public Long createOperationEndCompany(OperationEndCompanySaveReqVO createReqVO) {
        // 插入
        OperationEndCompanyDO operationEndCompany = BeanUtils.toBean(createReqVO, OperationEndCompanyDO.class);
        operationEndCompanyMapper.insert(operationEndCompany);
        // 返回
        return operationEndCompany.getId();
    }

    @Override
    public void updateOperationEndCompany(OperationEndCompanySaveReqVO updateReqVO) {
        // 校验存在
        validateOperationEndCompanyExists(updateReqVO.getId());
        // 更新
        OperationEndCompanyDO updateObj = BeanUtils.toBean(updateReqVO, OperationEndCompanyDO.class);
        operationEndCompanyMapper.updateById(updateObj);
    }

    @Override
    public void deleteOperationEndCompany(Long id) {
        // 校验存在
        validateOperationEndCompanyExists(id);
        // 删除
        operationEndCompanyMapper.deleteById(id);
    }

    private void validateOperationEndCompanyExists(Long id) {
        if (operationEndCompanyMapper.selectById(id) == null) {
            throw exception(OPERATION_END_COMPANY_NOT_EXISTS);
        }
    }

    @Override
    public OperationEndCompanyDO getOperationEndCompany(Long id) {
        return operationEndCompanyMapper.selectById(id);
    }

    @Override
    public List<String> getSelfAndSubCompanyIds(String companyId) {
        return operationEndCompanyMapper.getSelfAndSubCompanyIds(companyId);
    }

    @Override
    public Map<String, String> getAllCompanyIdAndName() {
        List<OperationEndCompanyDO> operationEndCompanyDOS = operationEndCompanyMapper.selectList();
        if(CollectionUtils.isNotEmpty(operationEndCompanyDOS)){
            return operationEndCompanyDOS.stream().collect(Collectors.toMap(OperationEndCompanyDO::getCompanyId, OperationEndCompanyDO::getName));
        }
        return new HashMap<>();
    }

    @Override
    public Map<String, String> getCompanyIdAndNameMap(List<String> companyIds) {
        if(CollectionUtils.isNotEmpty(companyIds)){
            List<OperationEndCompanyDO> operationEndCompanyDOS = operationEndCompanyMapper.selectList(
                    new LambdaQueryWrapper<OperationEndCompanyDO>()
                            .in(OperationEndCompanyDO::getCompanyId, companyIds)
            );
            if(CollectionUtils.isNotEmpty(operationEndCompanyDOS)){
                return operationEndCompanyDOS.stream().collect(Collectors.toMap(OperationEndCompanyDO::getCompanyId, OperationEndCompanyDO::getName));
            }
        }
        return new HashMap<>();
    }

    @Override
    public PageResult<OperationEndCompanyDO> getOperationEndCompanyPage(OperationEndCompanyPageReqVO pageReqVO) {
        return operationEndCompanyMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OperationEndCompanyRespVO> getAllOperationEndCompany() {
        List<OperationEndCompanyRespVO> voList = new ArrayList<>();
        LambdaQueryWrapper<OperationEndCompanyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(OperationEndCompanyDO::getOrderNum);
        List<OperationEndCompanyDO> alldos = operationEndCompanyMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(alldos)){
            // 查找一级
            int index = 0;
            int max = alldos.size()+100;
            for (OperationEndCompanyDO operationEndCompanyDO : alldos) {
                if (operationEndCompanyDO.getLevel() == 1) {
                    OperationEndCompanyRespVO level1 = BeanUtils.toBean(operationEndCompanyDO, OperationEndCompanyRespVO.class);
                    level1.setChildren(new ArrayList<>());
                    voList.add(level1);
                    // 查找二级
                    for (OperationEndCompanyDO operationEndCompanyDO2 : alldos) {
                        if (operationEndCompanyDO2.getLevel() == 2 && operationEndCompanyDO2.getBelongLevel1Id().equals(operationEndCompanyDO.getId())) {
                            OperationEndCompanyRespVO level2 = BeanUtils.toBean(operationEndCompanyDO2, OperationEndCompanyRespVO.class);
                            level2.setChildren(new ArrayList<>());
                            level1.getChildren().add(level2);
                            // 查找三级
                            for (OperationEndCompanyDO operationEndCompanyDO3 : alldos) {
                                if (operationEndCompanyDO3.getLevel() == 3 && operationEndCompanyDO3.getBelongLevel2Id().equals(operationEndCompanyDO2.getId())) {
                                    OperationEndCompanyRespVO level3 = BeanUtils.toBean(operationEndCompanyDO3, OperationEndCompanyRespVO.class);
                                    level2.getChildren().add(level3);
                                    index ++ ;
                                    // 可能有未知循环存在，三级不可能比所有的数据还多
                                    if(index > max){
                                        throw new BusinessException("数据异常，请联系管理员查看");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return voList;
    }

    @Override
    public OperationEndCompanyDO getByCompanyId(String companyId) {
        List<OperationEndCompanyRespVO> voList = new ArrayList<>();
        LambdaQueryWrapper<OperationEndCompanyDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OperationEndCompanyDO::getCompanyId,companyId);
        List<OperationEndCompanyDO> alldos = operationEndCompanyMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(alldos)){
            return alldos.get(0);
        }
        return null ;
    }

    @Override
    public String getCompanyName(String companyId) {
        OperationEndCompanyDO byCompanyId = getByCompanyId(companyId);
        return null==byCompanyId?null:byCompanyId.getName();
    }
}